#include <Windows.h>
#include <tchar.h>
#include <stdio.h>

class CSub 
{
public:
	CSub()
	{
		_tprintf(_T("CSub constructor\n"), this);
	}
	
	~CSub()
	{
		_tprintf(_T("CSub destructor\n"), this);
	}
	
	void Print()
	{
		_tprintf(_T("Print: 0X%6X\n"), this);
	}

	void* operator new(size_t nSize)
	{
		void* p = NULL;
		if (NULL == m_hHeap)
		{
			m_hHeap = HeapCreate(HEAP_NO_SERIALIZE, 0, 0);
		}
		p = HeapAlloc(m_hHeap, 0, nSize);
		if (NULL != p) 
		{
			m_nCount++;
			_tprintf(_T("Create instance 0x%6X\n"), p);
		}
		return p;
	}
	
	void operator delete(void* p)
	{
		if (NULL != p && HeapFree(m_hHeap, 0, p))
		{
			m_nCount--;
			_tprintf(_T("Destroy instance 0x%6X\n"), p);
		}

		if (0 == m_nCount && HeapDestroy(m_hHeap))
		{
			m_hHeap = NULL;
		}
	}

private:
	static HANDLE	m_hHeap;	
	static int		m_nCount;
};

HANDLE  CSub::m_hHeap		= NULL;
int		CSub::m_nCount		= NULL;

void main()
{
	CSub* pSub1 = new CSub;
	pSub1->Print();

	CSub* pSub2 = new CSub;
	pSub2->Print();	
	
	_tprintf(_T("------------------------------------\n"));

	delete pSub1;
	delete pSub2;

	system("pause");

	return;
}
